﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
using Kaskelot.SP.Services;
using Kaskelot.Web.ClientModel;
using Kaskelot.Web.Services;
using Stockholm.SOA.Kaskelot.WCF.DataContracts;

namespace Kaskelot.Web.ClientServices
{
	[ServiceContract(Namespace = "http://stockholm.se/Client/Kaskelot/ClientServices/", Name = "ClientBlankettService")]
	[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
	public class ClientBlankettService
	{
		[OperationContract]
		[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
		public ClientServiceResult<string> SendBlankett(ClientBlankett blankett)
		{
			ClientServiceResult<string> csr = new ClientServiceResult<string>();

			try
			{
				if (blankett != null)
				{
					using (WebService svc = new WebService())
					{
						var x = svc.GetBlankettById(new Guid(blankett.Id));

						BlankettPost blankettPost = new BlankettPost()
						{
							Id = Guid.NewGuid(),
							ValId = WebContext.Current.Val.Id,
							Blankett = new Blankett { Id = new Guid(blankett.Id) },
							PersonId = null,
							Skapad = DateTime.Now,
							Andrad = default(DateTime?),
							Status = BlankettPostStatus.Inkommen.ToString()
						};

						FaltData[] faltData = ParseFaltData(blankettPost.Id, blankett.FaltData);

						if (x != null && x.Typ == BlankettTyp.Epostformulär)
						{
							try
							{
								NotifieringsResultat svar = svc.SkickaEpost(blankettPost, faltData);

                                if (svar != null && svar.Fel == true)
                                {
                                    csr.HasError = true;
                                    csr.ErrorMessage = "Kunde inte skicka meddelandet. Försök igen senare.";
                                    csr.WarningMessage = svar.FelKod + ": " + svar.Meddelande;
                                }
                                else if (svar == null)
                                {
                                    csr.HasError = true;
                                    csr.ErrorMessage = "Kunde inte skicka meddelandet. Försök igen senare.";
                                    csr.WarningMessage = "NotifieringsResultat = null";
                                }
							}
							catch (Exception ex)
							{
								csr.HasError = true;
								csr.ErrorMessage = "Kunde inte skicka meddelandet. Försök igen senare.";
                                csr.WarningMessage = ex.ToString();
							}
						}
						else
						{
							svc.CreateBlankettPost(blankettPost);
							svc.SetFaltDataForBlankettPost(blankettPost.Id, faltData);
						}
					}
				}
			}
			catch (Exception ex)
			{
				csr.ErrorMessage = ex.Message;
				csr.HasError = true;
			}

			return csr;
		}

		private FaltData[] ParseFaltData(Guid blankettPostId, ClientFaltData[] blankett)
		{
			List<FaltData> faltData = new List<FaltData>();
			int i = 1;
			foreach (ClientFaltData falt in blankett)
			{
				if (falt.Id == null)
					continue;

				string data = "";
				foreach (string d in falt.Data)
				{
					if (string.IsNullOrEmpty(data))
						data = d;
					else
						data += ";" + d;
				}

				faltData.Add(new FaltData
				{
					Id = Guid.NewGuid(),
					Data = data,
					ValId = WebContext.Current.Val.Id,
					Falt = new Falt
					{
						Id = new Guid(falt.Id)
					},
					BlankettPostId = blankettPostId,
					RadIndex = i++
				});
			}

			return faltData.ToArray();
		}
	}
}